package com.ruoyi.web.controller.sms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.form.SmsBody;
import com.ruoyi.service.ISmsService;

import cn.hutool.core.util.RandomUtil;

@RestController
@RequestMapping("/sms")
public class AliyunSmsController {
	
	private static final Logger log = LoggerFactory.getLogger(AliyunSmsController.class);
	
	@Autowired
	private RedisCache redisCache;
	
	@Autowired
	private ISmsService smsService;
	
	@Anonymous
	@PostMapping("/sendSms")
    public AjaxResult sendSms(@RequestBody SmsBody sms){
        try {
        	List<String> phones = new ArrayList<>();
        	phones.add(sms.getPhone());
        	Map<String,String> params = new HashMap<>();
        	String verCode = RandomUtil.randomNumbers(6);
        	String verKey = StringUtils.randomUUID();
        	params.put("code", verCode);
        	System.out.println("Code:"+verCode);
        	// 存入redis并设置过期时间为30分钟 
        	redisCache.setCacheObject(Constants.CAPTCHA_CODE_KEY + verKey, verCode, 30L, TimeUnit.MINUTES);
        	String body = smsService.sendSms(phones, params);
        	System.out.println(body);
			String message = "";
			String code = "OK";
			if("OK".equals(code)){
				return AjaxResult.success().put("msg", message).put("key", verKey);
			}else{
				return AjaxResult.error(message);
			}
		} catch (Exception e) {
			log.error("短信发送失败", e);
			return AjaxResult.error(e.getMessage());
		}
    }

}
